<?php
/**
 * 解析fba每日库存(保留库存)-数据入库
 *（Logic）
 */
namespace App\Logic\Amazon\Api\Parse;

use App\Models\Amazon\FbaReservedInventory;

class GetReservedInventoryData
{
    /**
     * @param $lines
     * @param $accountId
     * @param $countryId
     * @return int
     */
    public static function exe($lines,$accountId,$countryId){
        if(!is_array($lines))return 2;
        if(!$countryId)return 2;
        FbaReservedInventory::query()->where('account_id',$accountId)->where('country_id',$countryId)->delete();
        $i = 0;
        $count = 0;
        try{
            foreach($lines as $line){
                $flag = self::_addReservedInventory($line,$accountId,$countryId);
                $flag && $count++;
                $i++;
            }
        }catch (\Exception $e){
            report($e);
        }
        return $i == $count ? 1 : 2;
    }

    /**
     * @param $line
     * @param $accountId
     * @param $countryId
     * @return bool
     */
    private static function _addReservedInventory($line,$accountId,$countryId){
        $count = FbaReservedInventory::query()
            ->where('country_id',$countryId)
            ->where('sku',$line['sku'])
            ->count();

        if($count > 0){
            $flag = FbaReservedInventory::query()
                ->where('country_id',$countryId)
                ->where('sku',$line['sku'])
                ->update(
                    [
                        'account_id' => $accountId,
                        'fnsku' => $line['fnsku'],
                        'asin' => $line['asin'],
                        'reserved_qty' => $line['reserved_qty'],
                        'reserved_customerorders' => $line['reserved_customerorders'],
                        'reserved_fc_transfers' => $line['reserved_fc-transfers'],
                        'reserved_fc_processing' => $line['reserved_fc-processing'],
                    ]
                );
            return !$flag ? false : true;
        }else{
            $re = FbaReservedInventory::query()->create(
                [
                    'account_id' => $accountId,
                    'country_id' => $countryId,
                    'sku' =>  $line['sku'],
                    'fnsku' => $line['fnsku'],
                    'asin' => $line['asin'],
                    'reserved_qty' => $line['reserved_qty'],
                    'reserved_customerorders' => $line['reserved_customerorders'],
                    'reserved_fc_transfers' => $line['reserved_fc-transfers'],
                    'reserved_fc_processing' => $line['reserved_fc-processing'],
                ]
            );
            return !$re ? false : true;
        }
    }
}
